﻿using System;
using System.Collections.Generic;
using System.Linq;
using HappyBa.Core.Interfaces;

namespace HappyBa.Core.Validators
{
    public class TimeValidation : IValidator
    {
        public IEnumerable<ValidationResult> Validate(ValidationContext context)
        {
            foreach (var times in context.Metrics.UserTimes)
            {
                if (!context.Metrics.IsDeveloper(times.Key)) continue;
                if (!context.ActiveEmployees.Contains(times.Key.ToString())) continue;
                var logOnUserStories =
                    context.Metrics.UserStories.Where(x => times.Value.Any(y => x.Id == y.Assignable.Id)).ToArray();
                if (logOnUserStories.Any())
                {
                    yield return new ValidationResult(
                        string.Format("{0} have logged time on user stories: '{1}' ",
                            times.Key, string.Join(",", logOnUserStories.Select(x => x.Id))))
                    {
                        User = times.Key
                    };
                }
                var last = times.Value.OrderBy(x => x.Date).LastOrDefault();
                var today = DateTime.UtcNow.ToShortDateString();
                var lastNotToday = times.Value.OrderBy(x => x.Date).LastOrDefault(x => !string.Equals(x.Date.ToShortDateString(), today));
                if (last == null)
                {
                    yield return new ValidationResult(string.Format("{0} don't log time at all", times.Key))
                    {
                        User = times.Key
                    };
                    continue;
                }
                if ((DateTime.UtcNow-last.Date).TotalDays > 1)
                {
                    yield return new ValidationResult(string.Format("{0} have logged time {1:0.##} day(s) ago", times.Key, (DateTime.UtcNow - last.Date).TotalDays))
                    {
                        User = times.Key
                    };
                }
                if(lastNotToday==null)continue;
                var lastDayTime = times.Value.Where(x => Math.Abs((lastNotToday.Date - x.Date).TotalHours) < 12).Sum(x => x.Spent);
                if (lastDayTime != 8)
                {
                    yield return new ValidationResult(string.Format("{0} have logged {1:0.##}h on the previous day: {2}", times.Key, lastDayTime, lastNotToday.Date.ToShortDateString()))
                    {
                        User = times.Key
                    };
                }
            }
        }
    }
}
